package com.zyht.bank.service.impl;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.wx.util.JsonUtil;
import com.zyht.bank.model.PictureResult;
import com.zyht.bank.service.PictureService;
import com.zyht.common.util.ExceptionUtil;
import com.zyht.common.util.FtpUtil;
@Service
public class PictureServiceImpl implements PictureService{
	//@Value("${FTP_ADDRESS}")
	@Value("#{propertiesReader[FTP_ADDRESS]}")
	private String FTP_ADDRESS;
	@Value("#{propertiesReader[FTP_PORT]}")
	private Integer FTP_PORT;
	@Value("#{propertiesReader[FTP_USER_NAME]}")
	private String FTP_USER_NAME;
	@Value("#{propertiesReader[FTP_PASSWORD]}")
	private String FTP_PASSWORD;
	@Value("#{propertiesReader[FTP_BASE_PATH]}")
	private String FTP_BASE_PATH;
	@Value("#{propertiesReader[IMAGE_BASE_URL]}")
	private String IMAGE_BASE_URL;
	@Value("#{propertiesReader[FTP_PROJECT_PATH]}")
	private String FTP_PROJECT_PATH;
	

	@Override
	public PictureResult uploadPicture(MultipartFile uploadFile) {
		//判断上传图片是否为空
		if (null == uploadFile || uploadFile.isEmpty()) {
			return PictureResult.error("上传图片为空");
		}
		//取文件扩展名
		String originalFilename = uploadFile.getOriginalFilename();
		String ext = originalFilename.substring(originalFilename.lastIndexOf("."));
		//生成新文件名
		//可以使用uuid生成新文件名。
		//UUID.randomUUID()
		//可以是时间+随机数生成文件名
		String imageName = System.currentTimeMillis()+ new Random().nextInt(6)+"";
		//把图片上传到ftp服务器（图片服务器）
		//需要把ftp的参数配置到配置文件中
		//文件在服务器的存放路径，应该使用日期分隔的目录结构
		SimpleDateFormat sf = new SimpleDateFormat("yyyy"+File.separator+"MM"+File.separator+"dd");
		String filePath = FTP_PROJECT_PATH+File.separator+sf.format(new Date());
		try {
			FtpUtil.uploadFile(FTP_ADDRESS, FTP_PORT, FTP_USER_NAME, FTP_PASSWORD, 
					FTP_BASE_PATH, filePath, imageName + ext, uploadFile.getInputStream());
		} catch (Exception e) {
			e.printStackTrace();
			return PictureResult.error(ExceptionUtil.getStackTrace(e));
		}
		//返回结果，生成一个可以访问到图片的url返回
		return PictureResult.ok(IMAGE_BASE_URL + filePath + "/" + imageName + ext);
	}

	@Override
	public PictureResult uploadPictures(HttpServletRequest request,HttpServletResponse response) {
		List<String> urls=new ArrayList<String>();
		//创建一个通用的多部分解析器  
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());  
        //判断 request 是否有文件上传,即多部分请求 
        if(multipartResolver.isMultipart(request)){
        	//转换成多部分request    
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;  
            //取得request中的所有文件名  
            Iterator<String> iter = multiRequest.getFileNames(); 
            while(iter.hasNext()){
            	 MultipartFile uploadFile = multiRequest.getFile(iter.next());
            	 if (null == uploadFile || uploadFile.isEmpty()) {
 					return PictureResult.error("上传图片为空");
 				}
 				//取文件扩展名
 				String originalFilename = uploadFile.getOriginalFilename();
 				String ext = originalFilename.substring(originalFilename.lastIndexOf("."));
 				//生成新文件名
 				//可以使用uuid生成新文件名。
 				//UUID.randomUUID()
 				//可以是时间+随机数生成文件名
 				String imageName = System.currentTimeMillis()+ new Random().nextInt(6)+"";
 				//把图片上传到ftp服务器（图片服务器）
 				//需要把ftp的参数配置到配置文件中
 				//文件在服务器的存放路径，应该使用日期分隔的目录结构
 				SimpleDateFormat sf = new SimpleDateFormat("yyyy"+File.separator+"MM"+File.separator+"dd");
 				String filePath = FTP_PROJECT_PATH+File.separator+sf.format(new Date());
 				try {
 					FtpUtil.uploadFile(FTP_ADDRESS, FTP_PORT, FTP_USER_NAME, FTP_PASSWORD, 
 							FTP_BASE_PATH, filePath, imageName + ext, uploadFile.getInputStream());
 				} catch (Exception e) {
 					e.printStackTrace();
 					return PictureResult.error(ExceptionUtil.getStackTrace(e));
 				}
 				urls.add(IMAGE_BASE_URL + filePath + "/" + imageName + ext);
            }
        }else{
        	return PictureResult.error("请选择上传的文件!");
        }
        //var arrParse = JSON.parse(strify);将字符数组转成js数组
		return PictureResult.ok(JsonUtil.Object2Json(urls));
	}
	
	
}
